import UtilsModule from '../../utils/util'
import { xhlGet, xhlPatch } from '../../utils/request'

Page({
  data: {
    cartList: [],
    empty: true,
    totalSelect: false,
    totalNum: 0,
    totalPrice: 0
  },

  // 请求购物车数据
  getCartList() {
    xhlGet('/users', { id: wx.getStorageSync('info').id })
    .then(res => {
      this.setData({ cartList: res[0].cart, empty: res[0].cart.length ? false : true })
      console.log(this.data.cartList)

      // 计算一下所有的总体数据
      this.caclHandler()
    })
  },

  // 空购物车
  goHandler() {
    wx.switchTab({
      url: '/pages/Home/Home',
    })
  },

  // 计算函数
  caclHandler() {
    let totalNum = 0
    let totalPrice = 0
    let total = 0
    this.data.cartList.forEach(item => {
      if (item.is_select) {
        totalNum += item.number
        totalPrice += item.number * item.price
        total += 1
      }
    })
    this.setData({
      totalNum,
      totalPrice,
      totalSelect: total === this.data.cartList.length
    })
  },

  // 提交修改当前用户的购物车数据
  updateCartHandler() {
    xhlPatch('/users/' + wx.getStorageSync('info').id, { cart: this.data.cartList })
    .then(() => {
       wx.showToast({ title: '修改成功 ^_^' })
       // 重新请求最新的购物车列表
       this.getCartList()
    })
  },

  // 购买数量 ++
  addHandler(e) {
    // 哪一件商品
    const info = this.data.cartList.find(item => item.id === e.target.dataset.id - 0)
    info.number++
    this.updateCartHandler()
  },

  subHandler(e) {
    // 哪一件商品
    const info = this.data.cartList.find(item => item.id === e.target.dataset.id - 0)
    if (info.number <= 1) return
    info.number--
    this.updateCartHandler()
  },

  deleteItemHandler(e) {
    const index = this.data.cartList.findIndex(item => item.id === e.target.dataset.id - 0)
    this.data.cartList.splice(index, 1)
    this.updateCartHandler()
  },

  clearCartHandler() {
    this.setData({ cartList: [], empty: true })
    this.updateCartHandler()
  },

  // 全选状态改变
  selectAllChangeHandler(e) {
    this.data.cartList.forEach(item => item.is_select = !!e.detail.value.length)
    this.setData({ cartList: this.data.cartList })
    setTimeout(() => {
      this.updateCartHandler()
    }, 0)
  },

  // 删除所有已选中
  deleteSelectedHandler() {
    this.setData({ cartList: this.data.cartList.filter(item => item.is_select === false) })
    setTimeout(() => {
      this.updateCartHandler()
    }, 0)
  },

  // 单个的修改选中状态
  itemSelectedHandler(e) {
    const info = this.data.cartList.find(item => item.id === e.target.dataset.id - 0)
    info.is_select = !info.is_select
    this.updateCartHandler()
  },

  onShow() {
    UtilsModule.checkLogin({
      type: 'tabbar', // 'navigation'
      url: '/pages/Cart/Cart'
    })

    this.getCartList()
  }
})